package com.example.com.example.servlet;

import com.example.mapper.UserMapper;
import com.example.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/adduser")
public class AddUserServlet extends HttpServlet {


    SqlSessionFactory sqlSessionFactory;

    public AddUserServlet()
    {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 3. 创建SqlSessionFactory对象
        this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1. 获取参数
        String username = req.getParameter("username");
        String sex = req.getParameter("sex");
        String dateStr = req.getParameter("birthday");
        System.out.println(dateStr);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = null;
        try {
            birthday = df.parse(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        String address = req.getParameter("address");
        System.out.println(address);
        User u = new User(-1,username,birthday,sex,address,null);

        System.out.println(u);

        // 2.
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int result = userMapper.saveUser(u);
        System.out.println(result);

        sqlSession.commit();
        sqlSession.close();


        // 3.

        // 1) 直接打印结果   json     resp.getWriter().print()
        // 2） 请求转发      req.getRequestDispatcher("index.jsp").forward(req,resp);
        // 3)  跳转         resp.sendDirect("index")

        resp.sendRedirect("index");




    }
}
